package petshop.gui;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import petshop.classes.BancoDeDados;
import java.sql.*;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
 *
 * @author arthur
 */
public class JanelaLogin extends javax.swing.JFrame {


    /** Creates new form JanelaLogin */
    public JanelaLogin() {
        initComponents();
        this.setTitle("Login");
        ImageIcon logo = new ImageIcon("./imagens/logo-16.gif");
        this.setIconImage(logo.getImage());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        campoUsuario = new javax.swing.JTextField();
        botaoEntrar = new javax.swing.JButton();
        labelUsuario = new javax.swing.JLabel();
        labelSenha = new javax.swing.JLabel();
        campoSenha = new javax.swing.JPasswordField();
        labelImagem = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(270, 380));
        setResizable(false);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        campoUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                enter(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 130;
        gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5);
        getContentPane().add(campoUsuario, gridBagConstraints);

        botaoEntrar.setText("Entrar");
        botaoEntrar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                logar(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.ipadx = 50;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(botaoEntrar, gridBagConstraints);

        labelUsuario.setText("Usuário:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        getContentPane().add(labelUsuario, gridBagConstraints);

        labelSenha.setText("Senha:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);
        getContentPane().add(labelSenha, gridBagConstraints);

        campoSenha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                enter(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 130;
        gridBagConstraints.insets = new java.awt.Insets(2, 5, 5, 5);
        getContentPane().add(campoSenha, gridBagConstraints);

        labelImagem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/petshop/gui/logo-150.png"))); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(15, 10, 15, 10);
        getContentPane().add(labelImagem, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void logar(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_logar
        // TODO add your handling code here:
        if(!existemPendencias()){
            String usuario = this.campoUsuario.getText();
            String senha = String.valueOf(this.campoSenha.getPassword());
            if(login(usuario, senha)) {
                this.setVisible(false);
                JanelaPrincipal janela = new JanelaPrincipal();
                janela.setTitle("Petstore-" + usuario);
                // Get the size of the screen
                Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

                // Determine the new location of the window
                int w = janela.getSize().width;
                int h = janela.getSize().height;
                int x = (dim.width-w)/2;
                int y = (dim.height-h)/2;

                // Move the window
                janela.setLocation(x, y);
                janela.setVisible(true);
            }
        }
    }//GEN-LAST:event_logar

    private void enter(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_enter
        if(evt.getKeyChar() == KeyEvent.VK_ENTER){
            logar(null);
        }
    }//GEN-LAST:event_enter

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JanelaLogin().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoEntrar;
    private javax.swing.JPasswordField campoSenha;
    private javax.swing.JTextField campoUsuario;
    private javax.swing.JLabel labelImagem;
    private javax.swing.JLabel labelSenha;
    private javax.swing.JLabel labelUsuario;
    // End of variables declaration//GEN-END:variables

    private boolean login(String user, String senha) {
        try {
            String cmd = "SELECT user,senha FROM usuarios WHERE user='" + user + "'";
            ResultSet dados = BancoDeDados.statement.executeQuery(cmd);

            dados.next();
            String u = (String) dados.getObject(1);
            String s = (String) dados.getObject(2);
            if (user.equals(u)) {
                if (senha.equals(s)) {
                    System.out.println("Usuario conectado com exito.");
                    return true;
                } else {
                    JOptionPane.showMessageDialog(this.getContentPane(), "Senha Invalida");
                    return false;
                }
            } else {
                JOptionPane.showMessageDialog(this.getContentPane(), "Usuario invalido");
                return false;

            }

        } catch (SQLException e) {
            System.out.print(e);
            System.out.println("Erro do Sistema");
            return false;
        }
    }

    public boolean existemPendencias(){
        boolean pendencia = false;

        if(campoUsuario.getText().equals("")){
            JOptionPane.showMessageDialog(this.getContentPane(), "Preencha o campo de usuário");
            pendencia = true;
        } else if(String.valueOf(this.campoSenha.getPassword()).equals("")){
            JOptionPane.showMessageDialog(this.getContentPane(), "Preencha o campo de senha");
            pendencia = true;
        }

        return pendencia;
    }
}
